package com.authapi.sample.api.controller;

import com.authapi.sample.api.entity.Role;
import com.authapi.sample.api.entity.User;
import com.authapi.sample.api.model.Response.Common.Result;
import com.authapi.sample.api.model.Response.Common.ResultList;
import com.authapi.sample.api.model.Response.Role.QueryRoleRequest;
import com.authapi.sample.api.model.Response.User.QueryUserRequest;
import com.authapi.sample.api.service.impl.RoleServiceImpl;
import com.authapi.sample.api.service.impl.UserServiceImpl;
import com.authapi.sample.api.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Baomidou
 * @since 2024-09-26
 */
@RestController
@RequestMapping("/Role")
@Api(tags = "角色管理")
public class RoleController {
    @Autowired
    private RoleServiceImpl roleService;

    @GetMapping("/GetRole")
    public Result<Role> GetRole(String id){
        Role role = roleService.getById(id);
        return Result.Success(role);
    }

    @PostMapping("/AddRole")
    public Result<Role> addUser(@RequestBody Role role){
        if(role.getId()==null|| role.getId().isEmpty()){
            role.setId(UUID.randomUUID().toString().substring(0,6));
        }
        roleService.save(role);
        return Result.Success(role);
    }

    @PostMapping("/UpdateRole")
    public Result<Role> updateUser(@RequestBody Role role){
        roleService.updateById(role);
        return Result.Success(role);
    }

    @PostMapping("/DeleteRole")
    public Result<User> deleteUser(@RequestBody Role role){
        roleService.removeById(role.getId());
        return Result.Success(null);
    }

    @PostMapping("/QueryRole")
    public ResultList<List<Role>> QueryRole(@RequestBody QueryRoleRequest request){
        int pageIndex = PageUtil.getPageIndexFromHeader();
        int pageSize = PageUtil.getPageSizeFromHeader();
        Page<Role> page = new Page<>(pageIndex, pageSize);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if(!request.getName().isEmpty()){
            queryWrapper.eq("name", request.getName());
        }

        IPage<Role> rolePage = roleService.page(page,queryWrapper);
        int count =(int) roleService.count(queryWrapper);
        List<Role> result = rolePage.getRecords();
        return ResultList.Success(result, count);
    }
}
